package com.moogene.saad.gameplay.defender;

import com.moogene.android.R;
import com.moogene.android.engine.mmi.Book;
import com.moogene.android.engine.mmi.widget.IconButton;
import com.moogene.android.engine.mmi.widget.Widget;
import com.moogene.android.engine.mmi.widget.Widget.OnCancelListener;
import com.moogene.android.engine.mmi.widget.Widget.OnClickListener;

public class ControlButtons {
	private static ControlButtons sControlBtns;
	private final IconButton btnMove;

	private final IconButton btnTrash;

	private final IconButton btnDone;

	private Tower linkTower;

	private ControlButtons() {
		btnMove = new IconButton(R.drawable.btnround_bg, R.drawable.btn_move);
		btnTrash = new IconButton(R.drawable.btnround_bg, R.drawable.btn_trash);
		btnDone = new IconButton(R.drawable.btnround_bg, R.drawable.btn_done);
		btnMove.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(Widget v) {
				disappear();
				linkTower.setFixed(false);
			}
		});

		btnMove.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(Widget v) {
				disappear();
			}

		});

		btnTrash.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(Widget v) {
				remove();
			}
		});

		btnTrash.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(Widget v) {
				disappear();
			}

		});

		btnDone.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(Widget v) {
				disappear();
				linkTower.setFixed(true);
			}
		});

		btnDone.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(Widget v) {
				disappear();
			}

		});
	}

	static ControlButtons getInstance() {
		if (sControlBtns == null) {
			sControlBtns = new ControlButtons();
		}
		return sControlBtns;
	}

	void link(Tower t) {
		linkTower = t;
	}

	void show() {
		Tower t = linkTower;
		if (t.canDragFree()) {
			btnDone.setLocation(t.getX() - 100, t.getY() - 100);
			btnDone.popup();
			Book.getInstance().addLayer(btnDone);
		} else {
			btnMove.setLocation(t.getX() - 100, t.getY() - 100);
			btnMove.popup();
			Book.getInstance().addLayer(btnMove);
		}
		btnTrash.setLocation(t.getX() + 100, t.getY() - 100);
		btnTrash.popup();
		Book.getInstance().addLayer(btnTrash);
	}

	void disappear() {
		btnDone.shrink();
		btnMove.shrink();
		btnTrash.shrink();
	}

	boolean isInAction() {
		return btnDone.isFocused() || btnMove.isFocused()
				|| btnTrash.isFocused();
	}

	private void remove() {
		Book.getInstance().removeLayer(btnMove);
		Book.getInstance().removeLayer(btnTrash);
		Book.getInstance().removeLayer(btnDone);
		Book.getInstance().removeLayer(linkTower);
	}

}
